var cosjs = require('cosjs')
var debug = parseInt(process.argv[2] || 0);
var root  = __dirname;

var server = new cosjs.http();

server.set('debug', debug);
server.set('root',  root);
server.set('api',   'api');        //前端接口目录，相对于root
server.set('static','wwwroot');   //静态文件目录,相对于root
//IP信任列表
server.set('trust', ["119.15.138","127.0.0.1","10.96.29"]);
//MSGID 前端发送，后端原样返回
server.set("msgid","msgid");
server.set("post",false); //关闭POST数据
//为API附加公共属性
server.apiPack(function(req,res,api){
    //use sid(server id) on the api
    api.prototype.sid =  res.sid || 0;
    //use ejs as api.display
    api.prototype.display = function (tpl, data) {
        var ejs = require('ejs');
        var ext = require('path').extname(tpl);
        if (!ext) {
            tpl = tpl + '.html';
        }
        var file = root+'/view/'+tpl;
        var text = require('fs').readFileSync(file, 'utf8');
        var html = ejs.render(text, data);
        res.end(html);
    };
    //api.redirect
    api.prototype.redirect = function (url) {
        res.writeHead(301, { 'Location': url});
        res.end(url);
    }
});
//路由
if(debug > 0 ){
    server.router('/test/',function(req,res,name){
        res.sid = 1;
        var arr = name.split('/');
        return ['test',arr[2] || 'index'];
    } );
}
//地址：http://URL/Sn/api/fun  Sn中n为服务器ID，api为模块名称，全部在api（路径由config.api决定）文件夹中，fun为api中具体的function
var gameServApi = new RegExp('^\/(S[0-9]{1,3})\/([a-zA-Z0-9]{2,10})\/([a-zA-Z0-9]{2,10})(|\/)$', 'i') ;
server.router(gameServApi,function(req,res,args){
    res.sid = parseInt(args[1].substr(1),10);  //设置服务器ID
    return [args[2],args[3]];
} );

//session id 名称，
server.session('id','$id');
//session key 前缀
server.session('hkey','cache');
//session id保存方式，get方式下前端请求每次都需要带上$id=cookieID 这个参数，参数名由session.id来决定
server.session('idType',['get', 'cookie']);
//session 数据库（redis）配置
server.session('dbase',function(req,res){
    return "127.0.0.1:6379";
});

server.start(80);